package ar.com.ford.it.fullEconomics.persistence.dao.query;

import java.sql.Timestamp;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReportQuery;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese01Economic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese03Econvalue;
import com.ford.it.persistence.impl.toplink.CustomExpressionFactory;

public class FindEconomicValuesUpdatedLessDate implements
        CustomExpressionFactory {

    public Expression createExpression(ExpressionBuilder builder,
            Object[] parameters) {
        Teese03Econvalue ecoV = (Teese03Econvalue) parameters[0];
        Timestamp periodSelec = (Timestamp) parameters[1];
        Teese01Economic economic = ecoV.getTeese01Economic();
        String findState = ecoV.getEese03CreateUserC();
        Expression exp = null;
        Expression subQ = null;
        ExpressionBuilder builderReport = new ExpressionBuilder();
        ReportQuery report = new ReportQuery();
                
        report = new ReportQuery(Teese03Econvalue.class, builderReport);
        report.addMaximum("eese03EcvalueEffectivDateY", builderReport.get("eese03EcvalueEffectivDateY"));
        subQ =builderReport.get("teese01Economic").equal(economic);
        subQ = subQ.and(builder.get("eese03EcvalueEffectivDateY").lessThanEqual(periodSelec));
        report.setSelectionCriteria(subQ);
        exp = builder.get("eese03PlantCodeC").equal(
                economic.getEese01PlantCodeC());
        if (findState != null) {
            if ("aprobados".equals(findState))
                exp = exp.and(builder.get("eese03EcvalueApprovalS").notNull());
            if ("registrados".equals(findState))
                exp = exp.and(builder.get("eese03LastUserUpdtC").notNull());
        }
        exp = exp.and(builder.get("eese03EcvalueTypeCodeC").equalsIgnoreCase(ecoV.getEese03EcvalueTypeCodeC()));
        exp = exp.and(builder.get("teese01Economic").equal(economic));
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").equal(exp.subQuery(report)));
        
        return exp;
    }

}
